import { requestLogin,getAuthMenu} from '../../api/api';
// import Cookies from 'js-cookie';
const user = {
  state: {
    name: '',
    userId:'',
    // token:Cookies.get('token'),
    token:localStorage.getItem('token'),
    deptId:'',
    userDeptId:'',
  },

  mutations: {
    setDeptId: (state, deptId) => {
      state.deptId = deptId;
    },
    setUserDeptId: (state, userDeptId) => {
      state.userDeptId = userDeptId;
    },
    setName: (state, name) => {
      state.name = name;
    },
    setUserId: (state, userId) => {
      state.userId = userId;
    },
    setMobilePhone: (state, mobilePhone) => {
      state.mobilePhone = mobilePhone;
    },
    setToken(state,token) {
      localStorage.setItem('token', token)
      // Cookies.set('token',token);
      // localStorage.token = data
      state.token = token
    },
    logout(state){
      localStorage.removeItem('token');
      // Cookies.remove('token');
    }
  },

  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        requestLogin(userInfo).then(data => {
          if(data.success){
            const obj =data.attributes;
            commit('setToken', obj.token);
            resolve(data);
          }else{
            reject(data);
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 获取用户信息
    getinfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getAuthMenu({'parentId':'401882591499653120'}).then(data => {
          const obj =data.obj;
          commit('setName', obj.user.realName);
          commit('setUserId',obj.user.id);
          commit('setDeptId', obj.deptId);
          commit('setUserDeptId', obj.user.departId);
          commit('setMobilePhone', obj.user.mobilePhone);          
          resolve(data);
        }).catch(error => {
          reject(error);
        });
      });
    },


    // 登出
    // LogOut({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     logout(state.token).then(() => {
    //       commit('SET_TOKEN', '');
    //       commit('SET_ROLES', []);
    //       Cookies.remove('Admin-Token');
    //       resolve();
    //     }).catch(error => {
    //       reject(error);
    //     });
    //   });
    // },

    // 前端 登出
    LogOut({ commit }) {
      return new Promise(resolve => {
        commit('logout');
        commit('setToken','');
        commit('setUserId','');
        commit('setName', '');
        commit('setDeptId','');
        commit('setUserDeptId','');
        resolve();
      });
    },
  }
};

export default user;
